package moment;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utiles {
    public static WebDriver driver;
    public WebDriver createDriver(String url) {
        if (driver == null) {
            // 1. 使用驱动打开浏览器
            WebDriverManager.chromedriver().setup();
            // 增加浏览器, 创建驱动对象要强制允许访问所有的链接
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);
            driver.manage().window().maximize();
            driver.get(url);
            // 隐式等待， 作用于整个driver， 等待两秒，让他等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
        return driver;
    }
    public Utiles(String url) {
         driver = createDriver(url);
         driver.get(url);
    }
    /**
     * 截屏
     * @param str
     * @throws IOException
     */
    public void cutScreen(String str) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String fileName = "./src/test/image/" + dirTime + "/" + str + "-" + fileTime + ".png";
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(fileName));
    }




}
